<?php

namespace App\Console\Commands;

use App\Library\Logic\AfterSaleLogic;
use App\Library\YsdLib;
use Exception;
use Illuminate\Console\Command;
use Yansongda\Pay\Pay;

class AfterSaleRefundCommand extends Command
{
    /**
     * 拍卖售后退钱
     *
     * @var string
     */
    protected $signature = 'command:afterSaleRefund {serialNumber}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     * @throws Exception
     */
    public function handle(): void
    {
        $serialNumber = $this->argument('serialNumber');
        if (empty($serialNumber) || strlen($serialNumber) !== 20) return;
        $afterSale = AfterSaleLogic::findBySerialNumber($serialNumber);
        if (is_null($afterSale)) return;
        else if ($afterSale->status !== 1) return;
        else if (is_null($afterSale->agree_at)) return;
        else if (is_null($afterSale->paymentRelated)) return;
        else if (is_null($afterSale->payment)) return;
        $result = Pay::wechat(YsdLib::config())->refund([
            'transaction_id' => $afterSale->payment->out_trade_no,
            'out_trade_no' => $afterSale->paymentRelated->serial_number,
            'out_refund_no' => $afterSale->serial_number,
            'reason' => '退款',
            'notify_url' => config('app.url') . 'wechat/afterSaleRefund',
            'amount' => [
                'refund' => prod() ? (int)bcmul($afterSale->refund_price, 100) : 1,
                'total' => prod() ? (int)bcmul($afterSale->refund_price, 100) : 1,
                'currency' => 'CNY',
            ],
        ]);
        $afterSale->remit_at = now();
        $afterSale->status_arrival = 99;
        $afterSale->save();
        payLog($result->toArray());
    }
}
